<div class="game-container">
    <div class="game-info">
        <span>得分: <span id="snakeScore">0</span></span>
        <span>最高分: <span id="snakeHighScore">0</span></span>
    </div>
    <canvas id="snakeCanvas" class="game-canvas" width="400" height="400"></canvas>
    <div class="game-controls">
        <button class="btn btn-primary" onclick="startSnake()">开始游戏</button>
        <button class="btn btn-success" onclick="pauseSnake()">暂停</button>
    </div>
    <div class="text-center mt-4">
        <p class="text-sm text-gray-600">使用方向键或WASD控制方向</p>
    </div>
</div>

<script>
let snakeGame = {
    canvas: null,
    ctx: null,
    snake: [],
    food: {},
    direction: 'right',
    score: 0,
    highScore: 0,
    gameRunning: false,
    gameLoop: null
};

function initSnake() {
    snakeGame.canvas = document.getElementById('snakeCanvas');
    snakeGame.ctx = snakeGame.canvas.getContext('2d');
    
    // 初始化蛇
    snakeGame.snake = [{x: 10, y: 10}];
    snakeGame.direction = 'right';
    snakeGame.score = 0;
    
    // 生成食物
    generateFood();
    
    // 加载最高分
    const saved = localStorage.getItem('snakeHighScore');
    snakeGame.highScore = saved ? parseInt(saved) : 0;
    document.getElementById('snakeHighScore').textContent = snakeGame.highScore;
    
    // 监听键盘事件
    document.addEventListener('keydown', handleKeyPress);
    
    // 开始游戏循环
    if (snakeGame.gameLoop) clearInterval(snakeGame.gameLoop);
}

function generateFood() {
    snakeGame.food = {
        x: Math.floor(Math.random() * (snakeGame.canvas.width / 20)),
        y: Math.floor(Math.random() * (snakeGame.canvas.height / 20))
    };
}

function handleKeyPress(e) {
    const key = e.key.toLowerCase();
    const opposites = {
        'up': 'down',
        'down': 'up',
        'left': 'right',
        'right': 'left'
    };
    
    const newDirection = {
        'arrowup': 'up', 'w': 'up',
        'arrowdown': 'down', 's': 'down',
        'arrowleft': 'left', 'a': 'left',
        'arrowright': 'right', 'd': 'right'
    }[key];
    
    if (newDirection && newDirection !== opposites[snakeGame.direction]) {
        snakeGame.direction = newDirection;
    }
}

function updateSnake() {
    const head = {...snakeGame.snake[0]};
    
    switch(snakeGame.direction) {
        case 'up': head.y--; break;
        case 'down': head.y++; break;
        case 'left': head.x--; break;
        case 'right': head.x++; break;
    }
    
    // 检查碰撞
    if (head.x < 0 || head.x >= snakeGame.canvas.width / 20 ||
        head.y < 0 || head.y >= snakeGame.canvas.height / 20 ||
        snakeGame.snake.some(segment => segment.x === head.x && segment.y === head.y)) {
        gameOver();
        return;
    }
    
    snakeGame.snake.unshift(head);
    
    // 检查是否吃到食物
    if (head.x === snakeGame.food.x && head.y === snakeGame.food.y) {
        snakeGame.score += 10;
        document.getElementById('snakeScore').textContent = snakeGame.score;
        generateFood();
    } else {
        snakeGame.snake.pop();
    }
}

function drawSnake() {
    snakeGame.ctx.fillStyle = '#4ade80';
    snakeGame.snake.forEach(segment => {
        snakeGame.ctx.fillRect(segment.x * 20, segment.y * 20, 18, 18);
    });
}

function drawFood() {
    snakeGame.ctx.fillStyle = '#ef4444';
    snakeGame.ctx.beginPath();
    snakeGame.ctx.arc(
        snakeGame.food.x * 20 + 10,
        snakeGame.food.y * 20 + 10,
        8, 0, Math.PI * 2
    );
    snakeGame.ctx.fill();
}

function gameLoop() {
    if (!snakeGame.gameRunning) return;
    
    snakeGame.ctx.clearRect(0, 0, snakeGame.canvas.width, snakeGame.canvas.height);
    updateSnake();
    drawSnake();
    drawFood();
}

function startSnake() {
    if (!snakeGame.gameRunning) {
        snakeGame.gameRunning = true;
        snakeGame.gameLoop = setInterval(gameLoop, 100);
    }
}

function pauseSnake() {
    snakeGame.gameRunning = false;
    if (snakeGame.gameLoop) {
        clearInterval(snakeGame.gameLoop);
        snakeGame.gameLoop = null;
    }
}

function gameOver() {
    snakeGame.gameRunning = false;
    if (snakeGame.gameLoop) {
        clearInterval(snakeGame.gameLoop);
        snakeGame.gameLoop = null;
    }
    
    if (snakeGame.score > snakeGame.highScore) {
        snakeGame.highScore = snakeGame.score;
        localStorage.setItem('snakeHighScore', snakeGame.highScore);
        document.getElementById('snakeHighScore').textContent = snakeGame.highScore;
    }
    
    const name = prompt(`游戏结束！得分：${snakeGame.score}\n请输入你的名字：`);
    if (name && name.trim()) {
        submitScore('snake', name.trim(), snakeGame.score);
    }
    
    // 重置游戏
    initSnake();
}
</script>